
import 'package:flutter/services.dart';
import 'package:flutter_deer/index/iview/historical_expenditure_list_iview.dart';
import 'package:flutter_deer/index/models/com_code_entity.dart';
import 'package:flutter_deer/index/presenter/historical_expenditure_list_presenter.dart';
import 'package:flutter_deer/index/provider/historical_expenditure_list_page_provider.dart';
import 'package:flutter_deer/index/widgets/find_dropdown.dart';
import 'package:flutter_deer/mvp/base_page.dart';
import 'package:flutter_deer/mvp/power_presenter.dart';
import 'package:flutter/material.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/util/screen_utils.dart';
import 'package:flutter_deer/util/theme_utils.dart';
import 'package:flutter_deer/index/models/historical_expenditure_entity.dart';
import 'package:flutter_deer/widgets/fadein_text.dart';
import 'package:flutter_deer/widgets/my_refresh_list.dart';
import 'package:horizontal_data_table/horizontal_data_table.dart';
import 'package:flutter_deer/widgets/state_layout.dart';
import 'package:flutter_gen/gen_l10n/deer_localizations.dart';
import 'package:intl/intl.dart';
import 'package:lottie/lottie.dart';
import 'package:provider/provider.dart';

class HistoricalExpenditurePage extends StatefulWidget {
  const HistoricalExpenditurePage({super.key});

  @override
  _HistoricalExpenditurePageState createState() =>
      _HistoricalExpenditurePageState();
}

class _HistoricalExpenditurePageState extends State<HistoricalExpenditurePage>
    with
        BasePageMixin<HistoricalExpenditurePage, PowerPresenter>,
        TickerProviderStateMixin
    implements HistoricalExpenditureListIMvpView {
  final GlobalKey _bodyKey = GlobalKey();
  // 预算年度
  String fiscalYear = '2022';
  // 单位名称
  String agencyName = '';
  // 部门支出经济分类
  String depBgtEcoName = '请选择';
  // 资金性质
  String fundTypeName = '请选择';
  // 支出功能名称
  String expFuncName = '请选择';
  // 政府支出经济分类
  String govBgtEcoName = '请选择';
  final HDTRefreshController _hdtRefreshController = HDTRefreshController();
  late HistoricalExpenditureListPagePresenter
      historicalExpenditureListPagePresenter;
  HistoricalExpenditureListPageProvider provider =
      HistoricalExpenditureListPageProvider();
  @override
  PowerPresenter<dynamic> createPresenter() {
    final PowerPresenter<dynamic> powerPresenter =
        PowerPresenter<dynamic>(this);
    historicalExpenditureListPagePresenter =
        new HistoricalExpenditureListPagePresenter();
    powerPresenter.requestPresenter([historicalExpenditureListPagePresenter]);
    return powerPresenter;
  }

  @override
  void setHistoricalExpenditurePage(
      HistoricalExpenditurePageEntity? pageEntity) {
    provider.setHistoricalExpenditureItemPage(pageEntity);
  }

  @override
  void setFundTypeListPage(List<CodeMapEntity>? fundType) {
    provider.setCodeMap(fundType);
  }

  @override
  void setDepBgtEcoListPage(List<CodeMapEntity>? fundType) {
    provider.setDepBgtEcoCodeMap(fundType);
  }

  @override
  void setGovBgtEcoListPage(List<CodeMapEntity>? fundType) {
    provider.setGovBgtEcoCodeMap(fundType);
  }

  @override
  void setExpFuncListPage(List<CodeMapEntity>? fundType) {
    provider.setExpFuncCodeMap(fundType);
  }

  @override
  void initState() {
    super.initState();
    // 强制横屏
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
    if (mounted) {
      _onRefresh();
      _getFundTypeList();
      _getDepBgtEcoList();
      _getGovBgtEcoList();
      _getExpFuncList();
    }
  }

  @override
  void dispose() {
    // provider.dispose();
    super.dispose();
    // 强制竖屏
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
  }

  @override
  Widget build(BuildContext context) {
    final Color? iconColor = ThemeUtils.getIconColor(context);
    return ChangeNotifierProvider<HistoricalExpenditureListPageProvider>(
        create: (_) => provider,
        child: Consumer<HistoricalExpenditureListPageProvider>(
            builder: (_, provider, child) {
          return Scaffold(
              key: _bodyKey,
              appBar: AppBar(
                  leading: IconButton(
                    onPressed: () async {
                      FocusManager.instance.primaryFocus?.unfocus();
                      final isBack = await Navigator.maybePop(context);
                      if (!isBack) {
                        await SystemNavigator.pop();
                      }
                    },
                    tooltip: '${DeerLocalizations.of(context)!.back.nullSafe}',
                    padding: EdgeInsets.all(12.0),
                    icon: Image.asset(
                      Constant.backImg,
                      color: ThemeUtils.getIconColor(context),
                      height: 24,
                      width: 24,
                    ),
                  ),
                  title: Text('历史支付',
                      style: TextStyle(
                        fontSize: Dimens.font_sp18,
                        fontWeight: FontWeight.bold,
                        color:
                            context.isDark ? Colours.text_gray : Colours.text,
                      )),
                  centerTitle: true,
                  actions: <Widget>[
                    Builder(builder: (BuildContext appBarContext) {
                      return TextButton(
                        onPressed: () {
                          Scaffold.of(appBarContext).openDrawer();
                          print("点击下拉弹框图标");
                        },
                        child: Text(
                          '筛选',
                          style: TextStyle(color: Colors.black), // 根据需要设置文字颜色
                        ),
                      );
                    })
                  ]),
              drawer: Drawer(
                  child: GestureDetector(
                child: Container(
                  padding: const EdgeInsets.all(20),
                  margin: EdgeInsets.only(top: 6),
                  color: Colors.white,
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      // 年份选择
                      _yearSelect(provider),
                      // 单位名称
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text("单位名称"),
                          TextField(
                            decoration: InputDecoration(
                                contentPadding: const EdgeInsets.fromLTRB(
                                    16.0, 8.0, 16.0, 8.0),
                                hintText: "请输入",
                                border: InputBorder.none),
                            onChanged: (value) {
                              print(value);
                              setState(() {
                                agencyName = value;
                              });
                            },
                          ),
                        ],
                      ),

                      Container(
                        width: double.infinity,
                        height: 1.0,
                        color: Colors.grey[200],
                        margin: EdgeInsets.only(top: 5, bottom: 10),
                      ),
                      // 资金性质筛选
                      _select(provider),
                      Container(
                        width: double.infinity,
                        height: 1.0,
                        color: Colors.grey[200],
                        margin: EdgeInsets.only(top: 5, bottom: 10),
                      ),
                      // 部门支出经济筛选
                      _depSelect(provider),
                      Container(
                        width: double.infinity,
                        height: 1.0,
                        color: Colors.grey[200],
                        margin: EdgeInsets.only(top: 5, bottom: 10),
                      ),
                      // 政府支出经济分类筛选
                      _govSelect(provider),
                      Container(
                        width: double.infinity,
                        height: 1.0,
                        color: Colors.grey[200],
                        margin: EdgeInsets.only(top: 5, bottom: 10),
                      ),
                      // 支出功能分类筛选
                      _expSelect(provider),
                      Container(
                        width: double.infinity,
                        height: 1.0,
                        color: Colors.grey[200],
                        margin: EdgeInsets.only(top: 5, bottom: 10),
                      ),
                      SizedBox(height: 24),
                      ButtonBar(
                        alignment: MainAxisAlignment.center,
                        children: <Widget>[
                          TextButton(
                              style: ButtonStyle(
                                backgroundColor:
                                    MaterialStateProperty.all(Colors.white),
                                foregroundColor:
                                    MaterialStateProperty.all(Colors.blue),
                                shape: MaterialStateProperty.all(
                                  RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(3.0),
                                    side: BorderSide(
                                        color: Colors.blue,
                                        width: 1.0), // 边框颜色与宽度
                                  ),
                                ),
                              ),
                              child: Text('重置'),
                              onPressed: () {
                                setState(() {
                                  fiscalYear = '2022';
                                  agencyName = '';
                                  depBgtEcoName = '请选择';
                                  fundTypeName = '请选择';
                                  expFuncName = '请选择';
                                  govBgtEcoName = '请选择';
                                });
                                _onRefresh();
                                Navigator.pop(context);
                              }),
                          TextButton(
                            style: ButtonStyle(
                              backgroundColor:
                                  MaterialStateProperty.all(Colors.blue),
                              foregroundColor:
                                  MaterialStateProperty.all(Colors.white),
                              shape: MaterialStateProperty.all(
                                RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(3.0),
                                  side: BorderSide(
                                      color: Colors.blue,
                                      width: 1.0), // 边框颜色与宽度
                                ),
                              ),
                            ),
                            child: Text('确定'),
                            onPressed: () {
                              historicalExpenditureListPagePresenter
                                  .getHistoricalExpenditureList(
                                      fiscalYear,
                                      agencyName == '请选择' ? '' : agencyName,
                                      depBgtEcoName == '请选择'
                                          ? ''
                                          : depBgtEcoName,
                                      fundTypeName == '请选择' ? '' : fundTypeName,
                                      expFuncName == '请选择' ? '' : expFuncName,
                                      govBgtEcoName == '请选择'
                                          ? ''
                                          : govBgtEcoName);
                              Navigator.pop(context);
                            },
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                onTap: () {
                  setState(() {
                    // _selectIndex = null;
                  });
                },
              )),
              body: provider.list!.length > 0
                  ? Padding(
                    padding:EdgeInsets.all(20),
                    child: (
                        getDeerListView(provider)
                      ),
                    )   
                  : Container(
                      width: MediaQuery.of(context).size.width,
                      child: Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Lottie.asset('assets/lottie/no_football_game.json',
                                width: MediaQuery.of(context).size.width / 3,
                                fit: BoxFit.cover),
                            Gaps.vGap8,
                            FadeInText(
                                text:'暂无数据')
                          ],
                        ),
                      ),
                    ));
        }));
  }

  // 资金性质下拉组件
  Widget _yearSelect(HistoricalExpenditureListPageProvider provider) {
    int currentYear = DateTime.now().year;
    List<int> recentYears = List.generate(10, (index) => currentYear - index);
    return Container(
      child: FindDropdown(
        backgroundColor:Colors.white,
        label: '预算年度',
        searchHint: '搜索', 
        // constraints:BoxConstraints(minWidth: 20, minHeight: 10, maxHeight: 0, maxWidth: 30),
        items: recentYears,
        onChanged: (item) {
          print(item);
          setState(() {
            fiscalYear = item.toString();
          });
        },
        selectedItem: fiscalYear,
      ),
    );
  }

  // 资金性质下拉组件
  Widget _select(HistoricalExpenditureListPageProvider provider) {
    List<Map<String, dynamic>> code =
        provider.fundTypeCodeList!.map((e) => e.toJson()).toList();
    List<dynamic> codeList = code.map((e) => e['name']!).toList();
    return Container(
      child: FindDropdown(
        label: '资金性质',
        searchHint: '搜索',
        backgroundColor: Colors.white,       
        items: codeList,
        onChanged: (item) {
          print(item);
          setState(() {
            fundTypeName = item.toString();
          });
        },
        selectedItem: fundTypeName,
      ),
    );
  }

  // 部门支出经济分类名称列表组件
  Widget _depSelect(HistoricalExpenditureListPageProvider provider) {
    List<Map<String, dynamic>> code =
        provider.depBgtEcocodeList!.map((e) => e.toJson()).toList();
    List<dynamic> codeList = code.map((e) => e['name']!).toList();
    return Container(
      child: FindDropdown(
        label: '部门支出经济分类',
        backgroundColor: Colors.white,       
        searchHint: '搜索',
        items: codeList,
        onChanged: (item) {
          print(item);
          setState(() {
            depBgtEcoName = item.toString();
          });
        },
        selectedItem: depBgtEcoName,
      ),
    );
  }

  // 政府支出经济分类名称组件
  Widget _govSelect(HistoricalExpenditureListPageProvider provider) {
    List<Map<String, dynamic>> code =
        provider.govBgtEcocodeList!.map((e) => e.toJson()).toList();
    List<dynamic> codeList = code.map((e) => e['name']!).toList();
    return Container(
      child: FindDropdown(
        label: '政府支出经济分类',
        backgroundColor: Colors.white,       
        searchHint: '搜索',
        items: codeList,
        onChanged: (item) {
          print(item);
          setState(() {
            govBgtEcoName = item.toString();
          });
        },
        selectedItem: govBgtEcoName,
      ),
    );
  }

  // 支出功能分类名称列表
  Widget _expSelect(HistoricalExpenditureListPageProvider provider) {
    List<Map<String, dynamic>> code =
        provider.expFunccodeList!.map((e) => e.toJson()).toList();
    List<dynamic> codeList = code.map((e) => e['name']!).toList();
    return Container(
      child: FindDropdown(
        label: '支出功能分类',
        backgroundColor: Colors.white,       
        items: codeList,
        onChanged: (item) {
          print(item);
          setState(() {
            expFuncName = item.toString();
          });
        },
        selectedItem: expFuncName,
      ),
    );
  }

  HorizontalDataTable getDeerListView(
      HistoricalExpenditureListPageProvider provider) {
    int leftHeadCount = 1;
    List<String> headers = [
      '支付凭证主键',
      '资金性质代码',
      '资金性质名称',
      '预算年度',
      '凭证日期',
      '支付凭证号',
      '付款人全称',
      '付款人账号',
      '付款人开户银行',
      '收款人全称',
      '收款人账号',
      '收款人开户银行',
      '支付金额',
      '清算额度通知单号',
      '凭证号清单号',
      '划款凭证单号',
      '支出功能分类科目代码',
      '支出功能名称',
      '政府支出经济分类代码',
      '政府支出经济分类',
      '部门支出经济分类代码',
      '部门支出经济分类',
      '银行交易流水号',
      '实际支付金额',
      '实际支付日期',
      '单位代码',
      '单位名称',
      '用途',
      '结算方式代码',
      '结算方式名称',
      '项目代码',
      '项目名称',
      '财政区划代码',
      '财政区划名称',
      '外币金额',
      '币种代码',
      '币种',
      '汇率',
      '收款人代码',
      '回单附言',
      '实际收款人全称',
      '实际收款人账号',
      '实际收款人开户银行名称',
      '更新时间',
      '是否删除',
      '创建时间',
    ];
    List<String> columns = [
      'pay_cert_id',
      'fund_type_code',
      'fund_type_name',
      'fiscal_year',
      'vou_date',
      'pay_cert_no',
      'pay_acct_name',
      'pay_acct_no',
      'pay_acct_bank_name',
      'payee_acct_name',
      'payee_acct_no',
      'payee_acct_bank_name',
      'pay_amt',
      'lqd_quota_notice_no',
      'pay_cert_sum_no',
      'lqd_cert_no',
      'exp_func_code',
      'exp_func_name',
      'gov_bgt_eco_code',
      'gov_bgt_eco_name',
      'dep_bgt_eco_code',
      'dep_bgt_eco_name',
      'agent_business_no',
      'xpay_amt',
      'xpay_date',
      'agency_code',
      'agency_name',
      'use_des',
      'set_mode_code',
      'set_mode_name',
      'pro_code',
      'pro_name',
      'mof_div_code',
      'mof_div_name',
      'foreign_amt',
      'currency_code',
      'currency_name',
      'est_rat',
      'receiver_code',
      'receipt_add_word',
      'xpayee_acct_name',
      'xpayee_acct_no',
      'xpayee_acct_bank_name',
      'update_time',
      'is_deleted',
      'create_time'
    ];
    List<Container> headContainers = [];
    List<double> rightWidths = [];
    List<double> leftWidths = [];
    double rightWidth = 0;
    double leftWidth = 0;
    for (int i = 0; i < headers.length; i++) {
      double headWidth = Screen.calculateTextWidth(
              context, headers.elementAt(i), FontWeight.bold, 12, 300, 1) +
          10;
      if (i < leftHeadCount) {
        leftWidth += headWidth;
        leftWidths.add(headWidth);
      } else {
        rightWidth += headWidth;
        rightWidths.add(headWidth);
      }
      headContainers.add(Container(
        width: headWidth,
        height: 56,
        padding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
        alignment: Alignment.centerLeft,
        child: Text(headers.elementAt(i),
            style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 12)),
      ));
    }
    return HorizontalDataTable(
      leftHandSideColumnWidth: leftWidth,
      rightHandSideColumnWidth: rightWidth,
      isFixedFooter: false,
      isFixedHeader: true,
      headerWidgets: headContainers,
      footerWidgets: headContainers,
      leftHandSideColBackgroundColor: const Color(0xFFFFFFFF),
      rightHandSideColBackgroundColor: const Color(0xFFFFFFFF),
      enablePullToRefresh: true,
      refreshIndicator: const WaterDropHeader(),
      enablePullToLoadNewData: true,
      loadIndicator: const ClassicFooter(),
      htdRefreshController: _hdtRefreshController,
      onLoad: _loadMore,
      onRefresh: _onRefresh,
      rowSeparatorWidget: const Divider(
        color: Colors.black38,
        height: 1.0,
        thickness: 0.0,
      ),
      itemCount: provider.list!.length,
      leftSideItemBuilder: (context, index) {
        HistoricalExpenditureEntity doc = provider.list!.elementAt(index);
        List<Container> cells = [];
        for (int i = 0; i < leftWidths.length; i++) {
          cells.add(Container(
            width: leftWidths.elementAt(i),
            height: 52,
            padding: const EdgeInsets.fromLTRB(5, 0, 0, 0),
            alignment: Alignment.center,
            child: Text(
              doc.toJson()[columns.elementAt(i)].toString(),
              style: TextStyle(fontSize: 10),
            ),
          ));
        }
        return Row(
          children: cells,
        );
      },
      rightSideItemBuilder: (context, index) {
        HistoricalExpenditureEntity doc = provider.list!.elementAt(index);
        List<Container> cells = [];
        for (int i = 0; i < rightWidths.length; i++) {
          bool containsWord = columns[leftHeadCount + i].contains("amt");
          final numString = doc.toJson()[columns[leftHeadCount + i]] != null ? doc.toJson()[columns[leftHeadCount + i]] : '';
          final formatNum = containsWord ? NumberFormat.decimalPattern('en_us').format(double.parse(numString.toString())) : numString;
          print(containsWord);
          cells.add(Container(
            width: rightWidths.elementAt(i),
            height: 52,
            padding: const EdgeInsets.fromLTRB(5, 0, 0, 0),
            alignment: Alignment.center,
            child: Text(
              formatNum.toString(),
              style: TextStyle(fontSize: 10),
            ),
          ));
        }
        return Row(
          children: cells,
        );
      },
    );
  }

  Future<dynamic> _onRefresh() async {
    Future.delayed(Duration(seconds: 1), () {
      historicalExpenditureListPagePresenter.getHistoricalExpenditureList(
          fiscalYear,
          agencyName,
          depBgtEcoName == '请选择' ? '' : depBgtEcoName,
          fundTypeName == '请选择' ? '' : fundTypeName,
          expFuncName == '请选择' ? '' : expFuncName,
          govBgtEcoName == '请选择' ? '' : govBgtEcoName);
      ;
      _hdtRefreshController.loadComplete();
    });
  }

  Future<dynamic> _loadMore() async {
    Future.delayed(Duration(seconds: 1), () {
      historicalExpenditureListPagePresenter.getMoreIndentList(
          '2022', provider.currentPage! + 1);
      _hdtRefreshController.refreshCompleted();
    });
  }

  // 获取资金性质列表
  Future<dynamic> _getFundTypeList() async {
    Future.delayed(Duration(seconds: 1), () {
      historicalExpenditureListPagePresenter.getFundTypeList('');
      _hdtRefreshController.loadComplete();
    });
  }

  // 获取部门支出经济分类名称列表
  Future<dynamic> _getDepBgtEcoList() async {
    Future.delayed(Duration(seconds: 1), () {
      historicalExpenditureListPagePresenter.getDepBgtEcoList('');
      _hdtRefreshController.loadComplete();
    });
  }

  // 获取政府支出经济分类名称列表
  Future<dynamic> _getGovBgtEcoList() async {
    Future.delayed(Duration(seconds: 1), () {
      historicalExpenditureListPagePresenter.getGovBgtEcoList('');
      _hdtRefreshController.loadComplete();
    });
  }

  // 获取支出功能分类名称列表
  Future<dynamic> _getExpFuncList() async {
    Future.delayed(Duration(seconds: 1), () {
      historicalExpenditureListPagePresenter.getExpFuncList('');
      _hdtRefreshController.loadComplete();
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  bool get wantKeepAlive => false;
}
